const express = require('express');
const router = express.Router();
const neo4j = require('neo4j-driver');
const neo4jService = require('../services/neo4jService');

// 保存Neo4j设置
router.post('/neo4j', async (req, res) => {
  try {
    const { url, username, password, database } = req.body;
    
    if (!url || !username || !password) {
      return res.status(400).json({
        success: false,
        error: '缺少必要参数',
        message: '需要提供url、username和password'
      });
    }
    
    // 验证URL格式
    if (!url.startsWith('bolt://') && !url.startsWith('neo4j://') && !url.startsWith('neo4j+s://')) {
      return res.status(400).json({
        success: false,
        error: '无效的数据库地址',
        message: '数据库地址必须以bolt://、neo4j://或neo4j+s://开头'
      });
    }
    
    // 测试新的连接配置
    let testDriver;
    try {
      testDriver = neo4j.driver(
        url,
        neo4j.auth.basic(username, password),
        { database: database || 'neo4j' }
      );
      
      const testSession = testDriver.session();
      await testSession.run('RETURN 1');
      await testSession.close();
      
      // 如果测试成功，更新服务配置
      await neo4jService.updateConnection(url, username, password, database);
      
      res.json({
        success: true,
        message: 'Neo4j设置保存成功'
      });
      
    } catch (testError) {
      console.error('连接测试失败:', testError);
      res.status(400).json({
        success: false,
        error: '连接测试失败',
        message: testError.message
      });
    } finally {
      if (testDriver) {
        await testDriver.close();
      }
    }
    
  } catch (error) {
    console.error('保存Neo4j设置失败:', error);
    res.status(500).json({
      success: false,
      error: '保存设置失败',
      message: error.message
    });
  }
});

// 测试Neo4j连接
router.post('/test-connection', async (req, res) => {
  try {
    const { url, username, password, database } = req.body;
    
    if (!url || !username || !password) {
      return res.status(400).json({
        success: false,
        error: '缺少必要参数',
        message: '需要提供url、username和password'
      });
    }
    
    // 验证URL格式
    if (!url.startsWith('bolt://') && !url.startsWith('neo4j://') && !url.startsWith('neo4j+s://')) {
      return res.status(400).json({
        success: false,
        error: '无效的数据库地址',
        message: '数据库地址必须以bolt://、neo4j://或neo4j+s://开头'
      });
    }
    
    let testDriver;
    try {
      testDriver = neo4j.driver(
        url,
        neo4j.auth.basic(username, password),
        { database: database || 'neo4j' }
      );
      
      const testSession = testDriver.session();
      
      // 测试连接并获取数据库信息
      const result = await testSession.run('CALL dbms.components() YIELD name, versions, edition RETURN name, versions[0] as version, edition');
      await testSession.close();
      
      let version = 'Unknown';
      let edition = 'Unknown';
      
      if (result.records.length > 0) {
        const record = result.records[0];
        version = record.get('version') || 'Unknown';
        edition = record.get('edition') || 'Unknown';
      }
      
      res.json({
        success: true,
        message: '连接测试成功',
        version: version,
        edition: edition
      });
      
    } catch (testError) {
      console.error('连接测试失败:', testError);
      
      // 提供更友好的错误信息
      let errorMessage = testError.message;
      if (testError.code === 'ServiceUnavailable') {
        errorMessage = '无法连接到数据库服务器，请检查地址和端口是否正确';
      } else if (testError.code === 'Neo.ClientError.Security.Unauthorized') {
        errorMessage = '用户名或密码错误';
      } else if (testError.code === 'Neo.ClientError.Database.DatabaseNotFound') {
        errorMessage = '指定的数据库不存在';
      }
      
      res.status(400).json({
        success: false,
        error: '连接测试失败',
        message: errorMessage,
        code: testError.code
      });
    } finally {
      if (testDriver) {
        await testDriver.close();
      }
    }
    
  } catch (error) {
    console.error('测试连接失败:', error);
    res.status(500).json({
      success: false,
      error: '测试连接失败',
      message: error.message
    });
  }
});

// 获取当前Neo4j设置
router.get('/neo4j', (req, res) => {
  try {
    const currentSettings = neo4jService.getCurrentSettings();
    res.json({
      success: true,
      data: {
        url: currentSettings.url || process.env.NEO4J_URI,
        username: currentSettings.username || process.env.NEO4J_USERNAME,
        database: currentSettings.database || 'neo4j',
        // 不返回密码
        hasPassword: !!(currentSettings.password || process.env.NEO4J_PASSWORD)
      }
    });
  } catch (error) {
    console.error('获取设置失败:', error);
    res.status(500).json({
      success: false,
      error: '获取设置失败',
      message: error.message
    });
  }
});

module.exports = router;